package cn.wolfcode.web.controller;


import cn.wolfcode.ssm.domain.CourseOrder;
import cn.wolfcode.ssm.domain.Customer;
import cn.wolfcode.ssm.domain.SystemDictionaryItem;
import cn.wolfcode.ssm.query.CourseOrderQueryObject;
import cn.wolfcode.ssm.service.ICourseOrderService;
import cn.wolfcode.ssm.page.JsonPage;
import cn.wolfcode.ssm.service.ICustomerService;
import cn.wolfcode.ssm.service.ISystemDictionaryItemService;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/courseOrder")
public class CourseOrderController {

    @Autowired
    private ICourseOrderService courseOrderService;

    @Autowired
    private ICustomerService customerService;

    @Autowired
    private ISystemDictionaryItemService systemDictionaryItemService;


    @RequiresPermissions(value = {"courseOrder:list","课程订单管理页面"},logical = Logical.OR)
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") CourseOrderQueryObject qo){
        PageInfo<CourseOrder> pageResult = courseOrderService.query(qo);
        model.addAttribute("pageResult", pageResult);

        // 共享潜在客户数据
        List<Customer> customers = customerService.listAll();
        model.addAttribute("customers",customers);

        // 共享课程数据
        List<SystemDictionaryItem> subject = systemDictionaryItemService.selectParenSn("subject");
        model.addAttribute("subject",subject);

        return "courseOrder/list";
    }

    @RequestMapping("/delete")
    @RequiresPermissions(value = {"courseOrder:delete","课程订单管理删除"},logical = Logical.OR)
    @ResponseBody
    public JsonPage delete(Long id){
        if (id != null) {
            courseOrderService.delete(id);
        }
        return new JsonPage();
    }


    @RequestMapping("/saveOrUpdate")
    @RequiresPermissions(value = {"courseOrder:saveOrUpdate","课程订单管理新增/编辑"},logical = Logical.OR)
    @ResponseBody
    public JsonPage saveOrUpdate(CourseOrder courseOrder){
        if (courseOrder.getId() != null) {
            courseOrderService.update(courseOrder);
        }else {
            courseOrderService.save(courseOrder);

            // 插入后把当前潜在客户变成正式客户
            customerService.updateStatus(courseOrder.getCustomer().getId(),1);
        }
        return new JsonPage();
    }
}
